import { widgetManager } from '@/common/managers';
import { NMTopoBaseCommand } from '@/common/types';

import i18n from '@/common/utils/i18next';
import { DirectionType } from '@/components/DirectionField';
import { CmdDialogForm, ManagerId } from 'nextcae-base';

import { useEffect, useState } from 'react';

import { schema, uiSchema } from './schema';
import { TabsType } from './type';
import { TopoDialogProps } from '@/commands/topo/type';

import { PartMaterialField } from '@/components/PartMaterial';
import { EntityPartType } from '@amcax/web-render';

import { mesh } from '@/domain';

import { useRenderStore } from '@/common/store/renders';

import { message } from 'antd';

// 拉伸
function MeshExtrudeDialog({ title, onClose }: TopoDialogProps) {
  const mainRenderer = useRenderStore.getState().mainRenderer;
  const [hintMessage] = useState('进入拉伸体网格命令');
  const [formData, setFormData] = useState<any>({
    Tabs: TabsType.AssignDirection,
    Selection: {
      source: [],
      guide: [],
      guideType: 'node',
    },
    Options: {
      NumberOrSize: 'quantity',
      direction: [DirectionType.NormalToSource],
      distance: 1,
      count: 1,
      size: 1,
      reverse: false,
    },
  });
  useEffect(() => {
    widgetManager.hint(hintMessage);
    return () => {
      widgetManager.hint();
    };
  }, [hintMessage]);
  const isFormDataValid = () => {
    if (formData.Tabs === TabsType.AssignDirection) {
      return formData.Selection.source.length > 0;
    } else {
      // 引导线 node 最少2个,几何线一个
      const filterNode = formData.Selection.guide?.filter((item) => {
        return item.type === 'node';
      });
      const filterLine = formData.Selection.guide?.filter((item) => {
        return item.type === 'line';
      });
      return filterNode?.length > 1 || filterLine?.length > 0;
    }
  };
  const handleSubmit = async () => {
    const { Tabs, Selection, Options, AddTo } = formData;
    let params;
    let lineTwoPoints;
    if (Tabs === TabsType.AssignDirection) {
      params = {
        Source: Selection.source.map((item) => item.idx),
        Property: AddTo.property,
        Part: AddTo.part,
        Distance: Options.distance,
        DirMode: Options.direction.length == 1 ? 'SrcNormal' : 'UserDef',
        ...(Options.NumberOrSize === 'quantity' && { number: Options.count }),
        ...(Options.NumberOrSize === 'size' && { Dimension: Options.size }),
        ...(Options.direction.length == 2 && {
          Direction: Options.direction[1],
        }),
      };
      // distance/size 必须要能整除
      if (Options.NumberOrSize === 'size') {
        const isInteger = Number.isInteger(Options.distance / Options.size);
        if (!isInteger) {
          //
          message.error('distance必须要能整除size');
          return;
        }
      }
    } else {
      // 节点就选两个
      const nodePoint = Selection.guide
        .filter((item) => {
          return item.type === 'node';
        })
        .map((i) => i.point);
      // 几何线就选第一个
      const lineEntity = Selection.guide.filter((item) => {
        return item.type === 'line';
      })[0];
      if (lineEntity) {
        lineTwoPoints = mainRenderer
          .getEntityManager(ManagerId.Geometry)
          .getEntityData(lineEntity.dxid, EntityPartType.line, lineEntity.idx);
      }

      params = {
        Source: Selection.source.map((item) => item.idx),
        DirMode: nodePoint.length > 0 ? 'Node' : 'GeomCrv',
        Property: AddTo.property,
        Part: AddTo.part,
        ...(Options.NumberOrSize === 'quantity' && { number: Options.count }),
        ...(Options.NumberOrSize === 'size' && { Dimension: Options.size }),
        ...(nodePoint.length > 0 && { Nodes: nodePoint }),
        ...(lineEntity && {
          GeomCrv: Options.reverse
            ? [lineTwoPoints.slice(3, 6), lineTwoPoints.slice(0, 3)]
            : [lineTwoPoints.slice(0, 3), lineTwoPoints.slice(3, 6)],
        }),
      };
    }
    await mesh.extrudeMesh(params);
  };

  const handleFormDataChange = (data, id) => {
    if (!id) return;

    const keys = id.split('_');
    if (keys.length === 1) {
      setFormData((state) => ({
        ...state,
        Selection: {
          ...state.Selection,
          guideType: data.formData[keys[0]],
        },
      }));
    } else {
      setFormData((state) => {
        return {
          ...state,
          [keys[1]]:
            keys[1] === 'Tabs'
              ? data.formData[keys[1]]
              : { ...state[keys[1]], ...data.formData[keys[1]] },
        };
      });
    }
  };
  return (
    <CmdDialogForm
      title={title}
      formData={formData}
      titleIcon={'commands/mesh/extrude-mesh'}
      onSubmit={handleSubmit}
      // onPreview={handlePreview}
      onChange={handleFormDataChange}
      isFormDataValid={isFormDataValid()}
      schema={schema}
      fields={{
        partMaterialField: PartMaterialField,
      }}
      extraUiSchema={uiSchema}
      onClose={() => {
        onClose();
      }}></CmdDialogForm>
  );
}
// 拉伸
export const cmdMeshExtrude: NMTopoBaseCommand = {
  id: 'cmdMeshExtrude',
  icon: 'commands/mesh/extrude-mesh',
  label: 'command.mesh.extrudeMesh',
  create: (label: string, onClose: () => void, props) => (
    <MeshExtrudeDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
